package com.jie.deletefile.Contacts;

import android.content.Context;
import android.database.Cursor;
import android.provider.ContactsContract;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 13952137957 on 2016/11/11.
 */

public class ContactLogic {


    // These are the Contacts rows that we will retrieve.
    static final String[] CONTACTS_SUMMARY_PROJECTION = new String[] {
            ContactsContract.Contacts._ID,
            ContactsContract.Contacts.DISPLAY_NAME,
            ContactsContract.Contacts.PHOTO_ID,
    };

    /**
     * 获取手机系统联系人信息的静态方法-->亲测有效大笑
     * @return
     */
    public static List<ContactBean> getPhoneContacts(Context ctx) {
        List<ContactBean> contacts = new ArrayList<ContactBean>();
        String select = "((" + ContactsContract.Contacts.DISPLAY_NAME + " NOTNULL) AND ("
                + ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1) AND ("
                + ContactsContract.Contacts.DISPLAY_NAME + " != '' ))";
        try {
            Cursor cursor = ctx.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,
                    CONTACTS_SUMMARY_PROJECTION,
                    select,
                    null, ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
            while (cursor.moveToNext()) {
                int indexId = cursor.getColumnIndex(ContactsContract.Contacts._ID);
                String contactId = cursor.getString(indexId);
                int indexDisplayName = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
                String name = cursor.getString(indexDisplayName);


                Cursor phones = ctx.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
                ContactBean data = new ContactBean();
                data.setName(name);

                //一个人电话可能不止一个，所以可能是一个集合，因此在设置实体类的时候，手机号那里可以设置成一个集合，集合中放置Phone的实体类
                while (phones.moveToNext()) {
                    String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    data.setNumber(phoneNumber);
                }
                contacts.add(data);
                phones.close();
            }
            cursor.close();


            if(contacts != null) {
                //排序
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return contacts;
    }


}
